package com.wang.client;


import com.wang.handler.RpcClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 客户端
 * 1、连接Netty服务端
 * 2、提供调用者主动关闭资源的方法
 * 3、提供消息发送方法
 * Created by wangq on 2021/8/29.
 */
public class RpcClient {
    private EventLoopGroup group;

    private Channel channel;

    private String ip;

    private int port;

    private RpcClientHandler rpcClientHandler = new RpcClientHandler();

    private ExecutorService executorService = Executors.newCachedThreadPool();

    private long start;
    private long end;

    /**
     * 通信耗时
     */
    public long getCost() {
        return end - start;
    }

    public RpcClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
        initClient();
    }

    /**
     * 初始化方法-连接Netty服务端
     */
    public void initClient() {
        try {
            // 1、创建线程组
            group = new NioEventLoopGroup();

            // 2、创建启动助手
            Bootstrap bootstrap = new Bootstrap();

            // 3、设置参数
            bootstrap.group(group).channel(NioSocketChannel.class)
                    .option(ChannelOption.SO_KEEPALIVE, Boolean.TRUE) // 设置通道活跃状态
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000) // 设置通道超时时间
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            ChannelPipeline pipeline = socketChannel.pipeline();
                            // 添加String类型解码器
                            pipeline.addLast(new StringDecoder());
                            // 添加String类型编码器
                            pipeline.addLast(new StringEncoder());

                            // 添加客户端处理类
                            pipeline.addLast(rpcClientHandler);
                        }
                    });
            // 4、连接Netty服务端
            channel = bootstrap.connect(ip, port).sync().channel();

        } catch (InterruptedException e) {
            e.printStackTrace();
            if (channel != null) {
                channel.close();
            }
            if (group != null) {
                group.shutdownGracefully();
            }
        }

    }

    /**
     * 提供给调用者主动关闭资源
     */
    public void close() {
        if (channel != null) {
            channel.close();
        }
        if (group != null) {
            group.shutdownGracefully();
        }
    }

    /**
     * 提供消息发送方法
     *
     * @param msg 客户端发送的消息
     */
    public Object send(String msg) throws ExecutionException, InterruptedException {
        rpcClientHandler.setRequestMsg(msg);
        Future future = executorService.submit(rpcClientHandler);
        return future.get();
    }

}
